﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TwlEvent
{
    public class EventMgr : Singleton<EventMgr>
    {
        private Dictionary<string, List<EventDelegate>> map = null;

        protected override void initialize()
        {
            map = new Dictionary<string, List<EventDelegate>>();
        }

        public void addListener(string name, EventDelegate handler)
        {
            List<EventDelegate> list;
            if (map.TryGetValue(name, out list))
            {
                list.Add(handler);
            }
            else
            {
                list = new List<EventDelegate>();
                list.Add(handler);
            }
        }

        public void removeListener(string name, EventDelegate handler)
        {
            List<EventDelegate> list;
            if (map.TryGetValue(name, out list))
            {
                if (list.Contains(handler))
                    list.Remove(handler);
            }
        }

        public void dispatch(string name, Message msg) {
            List<EventDelegate> list;
            if (map.TryGetValue(name, out list))
            {
                for (int i = 0; i < list.Count; i++)
                {
                    list[i](msg);
                }
            }
        }

    }
}
